package study.web.blog;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Maps;

import study.domain.user.User;
import study.service.blog.FriendService;
import study.service.user.UserService;

@Controller
@RequestMapping("/blog/{usernmae}/friends")
public class FriendController {

	@Resource(name = "friendService")
	private FriendService friendService;

	@Resource(name = "userService")
	private UserService userService;

	@RequestMapping("")
	public String list(@PathVariable("username") String username, Model model) {
		User user = userService.getUserByUsername(username);
		if(user == null) {
			throw new RuntimeException("NOT FOUND user "+username);
		}
		List<User> following = friendService.findAllFollowing(user);
		List<User> follower = friendService.findAllFollower(user);
		model.addAttribute("following", following);
		model.addAttribute("follower", follower);
		return "blog/friends/list";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> addFriend(@PathVariable("username") String username,
			@RequestParam("username") String friendName) {
		Map<String, Object> results = Maps.newHashMap();
		results.put("error", true);
		User user = userService.getUserByUsername(username);
		if(user == null) {
			results.put("cause", "user_notfound '"+username+"'");
			return results;
		}
		User friend = userService.getUserByUsername(friendName);
		if(friend == null) {
			results.put("cause", "friend_notfound '"+friendName+"'");
			return results;
		}
		if(friendService.existsFollowing(user, friend)) {
			results.put("cause", "already_friend");
			return results;
		}
		friendService.add(user, friend);
		results.put("error", false);
		return results;
	}
}
